<template>
<div class="layout-app" ref='myBox'>
	<!-- main -->
<el-dialog :title="diglogTile" :visible.sync="exaDialogVisible" width="52%" :before-close="handleClose" :destroy-on-close='true' :modal="false"
:close-on-click-modal="false">
		<!-- 提交审核过单 -->
	<div class="addAcc">
			<!-- tabs -->
			<div class="tabs">
				<div class="tabsMain">
					<!-- 表单 -->
					<el-form ref="form" :model="addForm" label-width="128px" size="mini" :disabled="true" >
						<el-row :gutter="8">
							<el-col :xs="val.xs" :sm="val.xs" :md="val.md" :lg="val.lg" :xl="val.xl" type="flex" v-for="(val,i) in formType" :key="i">
								<!-- input -->
								<el-form-item v-if="val.type == 'input'" :label="val.label" :prop="val.modelValue">
									<el-input :suffix-icon='val.prefix' v-model="$data.addForm[val.modelValue]" :placeholder="val.placeholder"></el-input>
								</el-form-item>
								<!-- textarea -->
								<el-form-item v-if="val.type == 'textarea'" :label="val.label" :prop="val.modelValue">
									<el-input type="textarea" :rows="3" placeholder="请输入内容" v-model="$data.addForm[val.modelValue]"></el-input>
								</el-form-item>
								<!-- select -->
								<el-form-item v-if="val.type == 'select'" :label="val.label" :prop="val.modelValue">
									<el-select v-model="$data.addForm[val.modelValue]" filterable placeholder="请选择" :disabled="val.disabled">
										<el-option v-for="item in $data[val.op]" :key="item.id" :label="item.label" :value="item.id"> 
										<span style="color: #8492a6; font-size: 12px">{{ item.label }}</span></el-option>
									</el-select>
								</el-form-item>
								<!-- date -->
								<el-form-item v-if="val.type == 'date'" :label="val.label" :prop="val.modelValue">
									<el-date-picker  :disabled="val.disabled ? true : false"
									type="date" value-format="yyyy-MM-dd" placeholder="选择日期" v-model="$data.addForm[val.modelValue]">
									</el-date-picker>
								</el-form-item>
							</el-col>
						</el-row>
					</el-form>
					<!-- table -->
					<div class="table">
						<el-table :data="tableData" border @row-dblclick="handledbRow" :style="{ width: tableWidth + 'px' }">
							<el-table-column prop="drugId" label="药品序号" align='center'></el-table-column>
							<el-table-column prop="invyId" label="库存序号" align='center'></el-table-column>
							<el-table-column prop="docId" label="调拨序号" align='center'></el-table-column>
							<el-table-column prop="name" label="药品名称" align='center'></el-table-column>
							<el-table-column prop="purcType" label="库存类型">
								<template slot-scope="{ row }">
									<!-- 根据state显示不同的图标 -->
									<div class="stateValue" style="border-radius: 4px;text-align: center;">
										<span>{{ purcTypeMap[row.purcType] || '未知状态' }}</span>
									</div>
								</template>
							</el-table-column>
							<el-table-column prop="apllyAmt" label="调拨数量" align='center'>
								<template slot-scope="{ row }">
									<!-- 根据state显示不同的图标 -->
									<div class="stateValue" style="border-radius: 4px;text-align: center;">
										<span>{{ row.apllyAmt }}</span>
									</div>
								</template>
							</el-table-column>
							<el-table-column prop="unt" label="入库单位" align='center'></el-table-column>
							<el-table-column prop="purcPric" label="成本单价" align='center'></el-table-column>
							<el-table-column prop="purcAmt" label="成本金额" align='center'></el-table-column>
							<el-table-column prop="salePric" label="零售单价" align='center'></el-table-column>
							<el-table-column prop="saleAmt" label="零售金额" align='center'></el-table-column>
							
							<el-table-column prop="prodentpName" label="生产厂家" align='center' width="228"></el-table-column>
							<el-table-column prop="manuLotnum" label="生产批号" align='center' width="128"></el-table-column>
							
							<!-- <el-table-column v-for="(col, inx) in tableRows" :key="inx" :type="col.type" :prop="col.prop" :label="col.name" :width="columnWidth(col, tableData)"></el-table-column> -->
							<!-- fixed -->
							<el-table-column fixed="left" label="行号" type="index" width="68" align="center"></el-table-column>
						</el-table>
						<div class="total">
						  <span>成本合计金额：</span>
						  <el-input :value="cbValue | currencyFormat" style="width: 128px;" size="mini" :disabled='totaldisabled'></el-input>
						  <span style="margin-left: 12px;">零售合计金额：</span>
						  <el-input :value="lsValue | currencyFormat" style="width: 128px;" size="mini" :disabled='totaldisabled'></el-input>
						</div>
					</div>
				</div>
			</div>
			<!-- 提交 -->
			<div v-if="diglogTile === '草稿'" slot="footer" class="dialog-footer">
				<el-button size="mini" type="primary" @click="Submit">确定提交</el-button>
				<el-button size="mini" @click="exaDialogVisible = false">取消</el-button>
			</div>
			<!-- 审核 -->
			<div v-if="diglogTile === '审核'" slot="footer" class="dialog-footer">
				<el-button size="mini" type="danger" @click="refuseExamine">拒绝审核</el-button>
				<el-button size="mini" type="primary" @click="exaSubmit">确定审核</el-button>
				<el-button size="mini" @click="exaDialogVisible = false">取消</el-button>
			</div>
			<!-- 过单 -->
			<div v-if="diglogTile === '过单'" slot="footer" class="dialog-footer">
				<el-button size="mini" type="danger" @click="refusePassOrder">拒绝过单</el-button>
				<el-button size="mini" type="primary" @click="passOrderSubmit">确定过单</el-button>
				<el-button size="mini" @click="exaDialogVisible = false">取消</el-button>
			</div>
	</div>
</el-dialog>
</div>
</template>

<script>
// self
import AccType from './addAllocateType.js'
import addForm from './addForm.js' //Form表单
// prop

// ext

// 接口
import { changedpurcallocate,getdpurcallocate,findAttribute } from "@/api/systemCatalogue/Western.js";
export default {
	props: ['parentMethod'],
	inject: ['reload'], // 无痕刷新
	components:{
		
	},
	data(){
		return{
			//str
			diglogTile:'', // 动态页面的动态标题
			tableWidth:'', //右侧表格动态宽度
			totalAmt:'', //合计金额
			value:'',
			deptCode:'',
			cbValue:'',
			lsValue:'',
			getLunarDay: '',
			areaCode:'',
			areaPName:'',
			idx:'',
			//num
			
			//ble
			disabled:true,
			totaldisabled:true,
			exaDialogVisible:false,
			dialogFormVisible:false,
			//arr
			formType:[],
			tableData:[],
			selectOption:[{id:1,label:'西药库'},{id:2,label:'中药库'},{id:3,label:'西药房'},{id:4,label:'中药房'}],
			optionks:[{id:1,label:'西药库'},{id:2,label:'中药库'},{id:3,label:'西药房'},{id:4,label:'中药房'}],
			ghdwOption:[],
			nameOption:[],
			tableRows:[
				{ name:"药品名称", prop:"name" },{ name:"药品序号", prop:"drugId",  },
				{ name:"库存序号", prop:"invyId" },{ name:"调拨序号", prop:"docId"  },
				{ name:"调拨数量", prop:"apllyAmt", nz:"nz" },{ name:"成本单价", prop:"purcPric", type:"" },
				{ name:"成本金额", prop:"purcAmt", type:"" },{ name:"零售单价", prop:"salePric", type:"" },
				{ name:"零售金额", prop:"saleAmt", type:"" },{ name:'生产厂家',prop:'prodentpName'},
				{ name:'生产批号',prop:'manuLotnum'}
			],
			purcTypeMap: {
				1: '最小单位',
				2: '包装单位',
			},
			//obj
			addForm:{}, // form表单 * saleAmt
			options:[],
			ksOption:[],
			ssrOption:[],
			gysOption:[],
		}
	},
	mounted() {
		// 获取接口参数
		this.getAddForm();
		// 定义数据来源
		this.formType = AccType.map(function(val) { return val })
		// 获取制单人 => 当前登录用户
		// this.addForm.createId = JSON.parse(localStorage.getItem('userInfo')).userId;
	},
	methods:{
		// 打开model 获取采购计划数据
		async openModel(parm){
			this.diglogTile = parm.name
			this.exaDialogVisible = true;
			let res = await getdpurcallocate({id:parm.id });
			// res.data下的details 更名为addForm下detailsVOS
			for (let key in res.data) {
			  if (key === 'details') {
			    res.data['detailsVOS'] = res.data[key];
			    delete res.data[key];
			    break;
			  }
			}
			// this.addForm.phayId = res.data.phayId
			this.addForm = res.data
			this.addForm.busDate = '';
			// 计算总金额
			this.cbValue = res.data.costAmt;
			// 使用 reduce 方法将 saleAmt 的值相加
			this.lsValue = res.data.detailsVOS.reduce((total, item) => {
			  return total + parseFloat(item.saleAmt); // 将 saleAmt 转换为数字并累加
			}, 0); // 初始值为 0
			console.log(this.addForm,'获取合并之后的采购入库');
			this.tableData = res.data.detailsVOS

		},
		
		deleteRow(index, rows) {
		  rows.splice(index, 1);
		},
		// 科室档案
		async getKs(){
			let rs = await findAttribute()
			this.ksOption = rs.data.map(obj => {
			  // 将 name 替换为 label，并保留其他字段
			  return { label: obj.deptName , ...obj };
			});
			console.log(this.ksOption,'joiiasdoop');
		},
		testDate(val,i){
			this.idx = val.id
		},
		handleClose(done) {
			done();
		},
		// 确定提交
		async Submit(){
			console.log(this.addForm);
			let result = await changedpurcallocate({
				id:this.addForm.id,
				state: 2
			})
			if (result.code === 200) {
				this.reload(); // 更新数据驱动 => 父组件 shopPlan
				this.$message({ type: 'success', message: result.message});
				this.exaDialogVisible = false;
			} else {
				this.$message.error(result.message)
			}
		},
		//确定审核
		async exaSubmit(){
			console.log(this.addForm);
			let result = await changedpurcallocate({
				id:this.addForm.id,
				state: 4
			})
			if (result.code === 200) {
				this.reload(); // 更新数据驱动 => 父组件 shopPlan
				this.$message({ type: 'success', message: result.message});
				this.exaDialogVisible = false;
			} else {
				this.$message.error(result.message)
			}
		},
		// 拒绝审核
		refuseExamine(){
			this.$confirm('此操作将回退该条数据状态, 是否继续?', '提示', {
			  confirmButtonText: '确定',
			  cancelButtonText: '考虑一下',
			  type: 'warning'
			}).then(async() => {
				let result = await changedpurcallocate({
					id:this.addForm.id,
					state: 0
				})
				if (result.code === 200) {
					this.reload(); // 更新数据驱动 => 父组件 shopPlan
					this.$message({ type: 'success', message: result.message});
					this.exaDialogVisible = false;
				} else {
					this.$message.error(result.message)
				}
			}).catch(() => {
				this.$message({ type: 'info', message: '考虑一下'});          
			});
		},
		//确定过单
		async passOrderSubmit(){
			console.log(this.addForm,'过单数据');
			let result = await changedpurcallocate({
				id:this.addForm.id,
				state: 5
			})
			if (result.code === 200) {
				this.reload(); // 更新数据驱动 => 父组件 shopPlan
				this.$message({ type: 'success', message: result.message});
				this.exaDialogVisible = false;
			} else {
				this.$message.error(result.message)
			}
		},
		// 拒绝过单
		refusePassOrder(){
			this.$confirm('此操作将回退该条数据状态, 是否继续?', '提示', {
			  confirmButtonText: '确定',
			  cancelButtonText: '考虑一下',
			  type: 'warning'
			}).then(async() => {
				let result = await changedpurcallocate({
					id:this.addForm.id,
					state: 2
				})
				if (result.code === 200) {
					this.reload(); // 更新数据驱动 => 父组件 shopPlan
					this.$message({ type: 'success', message: result.message});
					this.exaDialogVisible = false;
				} else {
					this.$message.error(result.message)
				}
			}).catch(() => {
				this.$message({ type: 'info', message: '考虑一下'});          
			});
		},
		// 草稿保存
		async draftSubmit(){
			 this.addForm.list.push(this.lists)
			 this.addForm.totalAmt = this.cbValue
			 this.addForm.state = 0
			 console.log(this.addForm);
			 let result = await addPurchasingPlan(this.addForm)
			 if (result.code === 200) {
			 	this.reload(); // 更新数据驱动 => 父组件 shopPlan
			 	this.$message({ type: 'success', message: result.message});
			 	this.exaDialogVisible = false;
			 } else {
			 	this.$message.error(result.message)
			 }
		},
		//sons
		// db events
		handledbRow(row, column, event){
			if(row){ this.form = row; this.watchDialogVisible = true } else { console.log('fail'); }
			// console.log(this.form);
			this.formdisabled = true
			// this.form.textSpell = this.makePy(this.form.label).toLocaleUpperCase()
			// console.log(this.form.textSpell);
		},
		// col 里面包含了表头字段和名称，list 是表格数据
		columnWidth(col, list) {
		  let prop = col.prop,lab = col.lab;
		  let width = 40; // 设定一个最小值
		  let maxlenStr = ""; // 最长字符串
		  for (let info of list) {
			if (maxlenStr < (info[prop] + "").length) maxlenStr = info[prop];
		  }
		  width = Math.max(width, len(lab), len(maxlenStr));
		  // 表格自带的内边距(20px) 自调
		  return width + 24; // 这里加了 12px
		  function len(str) {
			// 实际分配长度可根据需要自行调整
			let length = 12;
			for (const char of str + "") {
			  // 英文小写字符 8px
			  if ("a" <= char && char <= "z") length += 8;
			  // 英文大写字符 8px
			  else if ("A" <= char && char <= "Z") length += 8;
			  // 中文字符 28px
			  else if (char >= "\u4e00" && char <= "\u9fa5") length += 28;
			  // 其他 8px
			  else length += 12;
			}
			return length;
		  }
		},
		// 挂载或销毁前后重新赋值后端参数
		getAddForm(){
			// 左侧提交表单
			this.addForm = addForm.map(v => {return v })[0]; // Form
			this.addMainForm = this.addForm.detailsVOS[0]
			this.getKs();
			// 定义数据来源
			this.formType = AccType.map(function(val) { return val })
			// 解构赋值排除 list 属性 => 弃用
			// this.addHeadrForm = addForm.map(item => { let { list, ...newItem } = item; return newItem })[0];
		},
	},
	
}
</script>

<style lang="less" scoped>
	/deep/ .el-dialog__header{
	    padding: 4px;
	    line-height: 28px;
	    background-color: #007bb0;
	}
	/deep/ .el-dialog__title{
	    color: #fff;
	    font-size: 12px;
	}
	/deep/ .el-dialog__headerbtn{
	    top: 10px;
	}
	/deep/ .el-dialog__body{
	    padding: 8px;
	}
	/deep/ .el-dialog__headerbtn .el-dialog__close{
	    color: #fff;
	}
.layout-app{
    width: 100%;
    height: 100%;
    display: flex;
	background-color: f8f8f8;
    .addAcc{
		
		/deep/ .el-form-item--mini.el-form-item, .el-form-item--small.el-form-item{
			margin-bottom: 8px;
		}
		/deep/ .el-dialog__title{
			color: #fff;
		}
		/deep/ .el-dialog__headerbtn .el-dialog__close{
			color: #fff;
		}
		/deep/ .el-dialog__headerbtn .el-dialog__close:hover{
			background-color: brown;
		}
		/deep/ .el-dialog__body{
			padding: 0;
		}
		/deep/ .el-divider--horizontal{
			margin: 0;
		}
		/deep/ .el-form-item__label{
			display: flex;
			justify-content: start;
			font-size: 12px;
		}
		// self
		// 选项卡
		.tabs{

			.tabsMain{
				display: flex;
				flex-direction: column;
				justify-content: space-between;
				align-items: center;
				margin-bottom: 8px;
				/deep/ .el-select> .el-input{
					// width: 118px;
				}
				/deep/ .el-input--mini .el-input__inner{
					height: 26px;
				}
				/deep/ .el-date-editor.el-input, .el-date-editor.el-input__inner{
					width: 100%;
				}
				border: 1px solid #EBEEF5;
				padding: 12px;
				/deep/ .el-form-item__label{
					display: flex;
					justify-content: start;
					font-size: 12px;
					width: 100%;
				}
				.a{
					flex: 1;
					display: flex;
					align-items: center;
				}
				.table{
					width: 100%;
					margin-top: 12px;
					/deep/ .el-table th{
						color: #2d2d2d;
						font-weight: bold;
						font-size: 12px;
						height: 18px;
						line-height: 18px;
					}
					/deep/ .el-table th.el-table__cell>.cell{
						// border-right: 2px solid #ececec;
						height: 18px;
						line-height: 18px;
						display: flex;
						align-items: center;
					}
					/deep/ .el-table td.el-table__cell div{
						font-size: 12px;
						height: 18px;
						line-height: 18px;
					}
					// padding: 16px;
					/* 自定义高亮颜色 */
					::v-deep .el-table__body tr.current-row > td {
					  background-color: #55aaff !important;
					  color: #f9f9f9; /* 可选：修改文字颜色 */
					}
				}
				.total{
					display: flex;
					height: 48px;
					align-items: center;
					span{
						font-size: 12px;
					}
				}
			}	
		}
		.dialog-footer{
			display: flex;
			justify-content: right;
		}
	}
}
</style>